#include"Seqlist.h"
//初始化顺序表
void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->size = 0；
    ps->capacity = 0;
}

//销毁顺序表
void SLDestroy(SL* ps)
{
	if (ps->arr)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

//检查空间是否够
void SLCheckCapacity(SL* ps)
{
	if (ps->capacity == ps->size)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLdatatpye* tmp = (SLdatatpye*)realloc(ps->arr, newcapacity * sizeof(SLdatatpye));
		assert(tmp);
		//空间申请成功
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
}

//从顺序表尾部插入
void SLPushBack(SL* ps, SLdatatpye x)
{
	assert(ps);
	//判断空间是否够
	SLCheckCapacity(ps);
	
	ps->arr[ps->size++] = x;
}

//从顺序表头部插入
void SLPushFront(SL* ps, SLdatatpye x)
{
	assert(ps);
	//判断空间是否够
	SLCheckCapacity(ps);
	for (int i = ps->size; i>0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;
}

//打印顺序表
void SLPrint(SL s)
{
	for (int i = 0; i < s.size; i++)
	{
		printf("%d  ", s.arr[i]);
	}
	printf("\n");
}

//顺序表尾删
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size);
	//顺序表不为空
	--ps->size;
}

//顺序表头删
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);

	//数据整体向前挪动
	for (int i = 0; i < ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps -> size--;
}

// 指定插入数据
void SLInsert(SL* ps, int pos, SLdatatpye x)
{
	assert(ps);
	assert(pos>=0&&pos<=ps->size);
	//插入数据前检查空间
	SLCheckCapacity(ps);
	//让pos后的数据后挪
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}

// 指定删除数据
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);

	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//顺序表的查找
int SLFind(SL* ps, SLdatatpye x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)return i; break;
	}
	return -1;
}